package com.advertisementsystem.Controller;

import com.advertisementsystem.Dto.LoginUser;
import com.advertisementsystem.Exception.ResponseResult;
import com.advertisementsystem.Mapper.ChatMessagesMapper;
import com.advertisementsystem.entity.ChatMessages;
import com.advertisementsystem.utils.SecurityUtils;
import com.alipay.api.domain.ChatMessage;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/notifications")
@Slf4j
public class NotificationController {

    @Autowired
    private ChatMessagesMapper chatMessageMapper;

    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

    /**
     * 获取设备拥有者的待处理通知
     * 将未读消息作为待办事项返回
     */
    @GetMapping("/pending")
    public ResponseResult<List<Map<String, String>>> getPendingNotifications() {
        try {
            Long currentUserId = getCurrentUserId();
            log.info("获取设备拥有者待处理通知 - userId: {}", currentUserId);

            LambdaQueryWrapper<ChatMessages> query = new LambdaQueryWrapper<>();
            query.eq(ChatMessages::getToUserId, currentUserId)
                    .eq(ChatMessages::getStatus, "SENT");
            // 获取未读消息作为待办事项
            List<ChatMessages> unreadMessages = chatMessageMapper.selectList(query);

            // 转换为前端需要的格式
            List<Map<String, String>> result = new ArrayList<>();
            for (ChatMessages message : unreadMessages) {
                Map<String, String> item = new HashMap<>();

                // 设置显示类型
                String displayType = getDisplayTypeByMessageType(message.getMessageType(), message.getNegotiationId());

                // 生成标题：优先使用消息内容，内容过长则截断
                String title = message.getContent();
                if (title != null && title.length() > 50) {
                    title = title.substring(0, 47) + "...";
                }
                item.put("type", displayType);
                item.put("title", title);
                item.put("time", message.getCreatedTime().format(TIME_FORMATTER));

                result.add(item);
            }

            return ResponseResult.success(result);
        } catch (Exception e) {
            log.error("获取待处理通知失败", e);
            return ResponseResult.error("获取待处理通知失败：" + e.getMessage());
        }
    }

    /**
     * 根据消息类型获取显示类型
     */
    private String getDisplayTypeByMessageType(String messageType, Long negotiationId) {
        if (messageType == null) {
            return "其他";
        }

        // 如果有协商ID，则显示为"协商"类型
        if (negotiationId != null) {
            return "协商";
        }

        switch (messageType) {
            case "NEGOTIATE":
                return "协商";
            case "SYSTEM":
                return "系统";
            case "FILE":
                return "文件";
            case "IMAGE":
                return "图片";
            case "TEXT":
            default:
                return "消息";
        }
    }

    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId() {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        return loginUser.getUser().getId();
    }
}